package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于死信的Java配置类 因为死信不能使用注解
 */
@Configuration
public class DeadLetterMqConfig {
    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //死信交换机
    @Bean
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }

    //死信队列
    @Bean
    public Queue deadLetterQueue() {
        Map<String, Object> arguments = new HashMap<>();
        //ttl 毫秒
        arguments.put("x-message-ttl", 12 * 1000);
        //过期转发的交换机
        arguments.put("x-dead-letter-exchange", exchange_dead);
        //过期转发的死信RoutingKey
        arguments.put("x-dead-letter-routing-key", routing_dead_2);
        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }

    //普通队列
    @Bean
    public Queue nQueue() {
        return QueueBuilder.durable(queue_dead_2).build();
    }

    //binding  本次只用一个死信交换机(实质应该还有一个普通交换机)
    @Bean
    public Binding bindingDeadLetterQueueToDeadLetterExchange(
            @Qualifier(value = "deadLetterQueue") Queue deadLetterQueue,
            @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange){
        return BindingBuilder.bind(deadLetterQueue).to(deadLetterExchange).with(routing_dead_1).noargs();
    }

    @Bean
    public Binding bindingNQueueToDeadLetterExchange(
            @Qualifier(value = "nQueue") Queue nQueue,
            @Qualifier(value = "deadLetterExchange") Exchange deadLetterExchange){
        return BindingBuilder.bind(nQueue).to(deadLetterExchange).with(routing_dead_2).noargs();
    }
}
